use log::error;
use std::sync::Mutex;
use tauri::{
    menu::{Menu, MenuItem},
    tray::TrayIconBuilder,
    AppHandle, Manager, Wry,
};
use tauri_plugin_opener::OpenerExt;

use crate::model::AppState;

use super::common;

pub fn init(app: AppHandle) -> tauri::Result<()> {
    let quit_menu = MenuItem::with_id(&app, "quit", "Quit", true, None::<&str>)?;
    let show_menu = MenuItem::with_id(&app, "show", "Show", false, None::<&str>)?;
    let hide_menu = MenuItem::with_id(&app, "hide", "Hide", true, None::<&str>)?;
    let open_menu = MenuItem::with_id(&app, "open", "Open", true, None::<&str>)?;
    let menu = Menu::with_items(&app, &[&hide_menu, &open_menu, &quit_menu])?;

    let mut builder = TrayIconBuilder::new();

    if let Some(icon) = app.default_window_icon() {
        builder = builder.icon(icon.clone());
    }
    let name = &app.package_info().name;

    builder
        .tooltip(name)
        .menu(&menu)
        .show_menu_on_left_click(true)
        .on_menu_event(move |app, event| {
            let message = match event.id.as_ref() {
                "quit" => common::app_exit(app),
                "hide" => handle_hide(app, &menu, &hide_menu, &show_menu),
                "open" => handle_open(app),
                "show" => handle_show(app, &menu, &hide_menu, &show_menu),
                _ => Err(format!("menu item {:?} was clicked", event.id)),
            };
            if let Err(err) = message {
                error!("{}", err);
            }
        })
        .build(&app)?;

    Ok(())
}

// 处理隐藏逻辑
fn handle_hide(
    app: &AppHandle,
    menu: &Menu<Wry>,
    hide_menu: &MenuItem<Wry>,
    show_menu: &MenuItem<Wry>,
) -> Result<(), String> {
    menu.remove(hide_menu).map_err(|e| e.to_string())?;
    menu.prepend(show_menu).map_err(|e| e.to_string())?;

    if let Some(window) = app.get_webview_window("main") {
        window.hide().map_err(|e| e.to_string())?;
    } else {
        return Err("Main window not found".to_string());
    }
    Ok(())
}

// 处理打开逻辑
fn handle_open(app: &AppHandle) -> Result<(), String> {
    let state = app.state::<Mutex<AppState>>();
    let state = state.lock().expect("Failed to acquire lock"); // 确保锁的快速释放
    let url = format!("http://localhost:{}", state.configs.common.port);

    app.opener()
        .open_url(url, None::<&str>)
        .map_err(|e| e.to_string())
}

// 处理显示逻辑
fn handle_show(
    app: &AppHandle,
    menu: &Menu<Wry>,
    hide_menu: &MenuItem<Wry>,
    show_menu: &MenuItem<Wry>,
) -> Result<(), String> {
    menu.remove(show_menu).map_err(|e| e.to_string())?;
    menu.prepend(hide_menu).map_err(|e| e.to_string())?;

    if let Some(window) = app.get_webview_window("main") {
        window.show().map_err(|e| e.to_string())?;
    } else {
        return Err("Main window not found".to_string());
    }
    Ok(())
}
